<template>
  <div class="edit-account">
    <el-form ref="form" :model="formData" class="form" :rules="rules">
      <el-form-item label="账号名" prop="name">
        <el-input v-model.trim="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="密码(留空不修改密码)" prop="password">
        <el-input v-model.trim="formData.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password_confirmation">
        <el-input v-model.trim="formData.password_confirmation" type="password"></el-input>
      </el-form-item>
      <el-button type="primary" @click="submit('form')">立即修改</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'EditAccount',
  data() {
    // 验证密码
    const checkPassword = (rule, value, callback) => {
      if (value.length > 0 && value.length < 6) {
        return callback(new Error('密码长度最少6个字符'))
      }
      callback()
    }
    // 验证确认密码
    const checkPasswordConfirmed = (rule, value, callback) => {
      if (value !== this.formData.password) {
        return callback(new Error('两次密码不一致'))
      }
      callback()
    }
    return {
      formData: {
        name: '',
        password: '',
        password_confirmation: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入账号名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { validator: checkPassword, trigger: 'blur' }
        ],
        password_confirmation: [
          { validator: checkPasswordConfirmed, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getUser()
  },
  methods: {
    /**
     * 获取用户信息
     */
    getUser() {
      this.$get('user/get')
        .then((res) => {
          this.formData.name = res.data.name
        })
    },
    /**
     * 提交修改
     */
    submit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const { name, password, password_confirmation } = this.formData
          this.$put('user/update', {
            name,
            password,
            password_confirmation
          })
            .then(() => {
              this.$message.success('修改成功')
            })
            .catch((error) => {
              this.$handleError(error)
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-account{
  .form{
    width: 400px;
  }
}
</style>
